<script setup lang="ts">
import {onActivated, onMounted, ref, useAttrs, useSlots, watch} from "vue";
import {ElCascader} from "element-plus";
import {devCascaderProps} from "./cascader";
import {devDeepMerge, devObjEstimation, useDevMethods} from "@/utils";
import {useConfig} from "@/index";

const attrs: Record<string, any> = useAttrs(); // 事件和属性
const props = defineProps(devCascaderProps)
const methods = useDevMethods();
const emit = defineEmits(['options-data', 'options-path']);
const slots = useSlots();
const options = ref<any>([]);
/**
 * 初始化
 */
const init = () => {
  // 解构赋值并设置默认值
  const {label = 'label', value = 'value', children = 'children'} = devDeepMerge(useConfig().elCascaderProps, attrs)?.props || {};

  // 处理API数据
  const handleApiData = async (list: any[]) => {
    emit('options-data', list);
    if (props.isDataProcessed) {
      const options_path = await devObjEstimation(list, value, label, children);
      emit('options-path', options_path);
    }
  };

  // 判断是否使用API
  if (props.useApi && props.api) {
    props.api(props.apiParams).then((res: any) => {
      const list = props.devCascaderFieldsFn
          ? props.devCascaderFieldsFn(res)
          : methods.devCascaderFieldsFn(res);
      options.value = list;
      handleApiData(list);
    });
  } else {
    handleApiData(attrs?.options || []);
  }
};

watch([() => attrs?.options, () => props.apiParams, () => props.useApi, () => props.api], () => {
  init();
})

onMounted(() => {
  if (props.onMounted && !props.onActivated) {
    init();
  }
})

onActivated(() => {
  if (props.onActivated) {
    init();
  }
})

// 定义组件名称
defineOptions({
  name: 'DevCascader',
  inheritAttrs: false
});
</script>

<template>
  <el-cascader v-bind="devDeepMerge(useConfig().elCascaderProps, $attrs)"
               v-if="props.useApi"
               :options="options">
    <template v-for="itemSlot in Object.keys(slots)" :key="itemSlot" v-slot:[itemSlot]="temp">
      <slot :name="itemSlot" v-bind="temp"></slot>
    </template>
  </el-cascader>
  <el-cascader v-bind="devDeepMerge(useConfig().elCascaderProps, $attrs)"
               v-else>
    <template v-for="itemSlot in Object.keys(slots)" :key="itemSlot" v-slot:[itemSlot]="temp">
      <slot :name="itemSlot" v-bind="temp"></slot>
    </template>
  </el-cascader>
</template>

<style scoped lang="scss">

</style>
